const express = require('express');
const router = express.Router();
const multer = require('multer');
const { protect } = require('../middlewares/authMiddleware');
const { 
  uploadFile, 
  publishPost, 
  getPosts, 
  getPostsPaged, 
  deletePost,
  getById,
  toggleLike 
} = require('../controllers/postController');

// 配置 multer 用于文件上传，使用内存存储
const storage = multer.memoryStorage();
const upload = multer({ 
  storage,
  limits: {
    fileSize: 50 * 1024 * 1024, // 将文件大小限制增加到50MB
    fieldSize: 50 * 1024 * 1024 // 将字段大小限制增加到50MB
  },
  fileFilter: (req, file, cb) => {
    if (file.size > 50 * 1024 * 1024) {
      cb(null, false); // 拒绝文件上传
      return;
    }
    cb(null, true); // 接受文件上传
  }
});

// 自定义错误处理中间件
const handleMulterError = (err, req, res, next) => {
  if (err instanceof multer.MulterError) {
    if (err.code === 'LIMIT_FILE_SIZE') {
      return res.status(400).json({ message: '文件太大，请上传小于50MB的文件' });
    }
  }
  next(err);
};

/**
 * @swagger
 * /posts/upload:
 *   post:
 *     summary: 上传文件
 *     tags: [Post]
 *     requestBody:
 *       required: true
 *       content:
 *         multipart/form-data:
 *           schema:
 *             type: object
 *             properties:
 *               file:
 *                 type: string
 *                 format: binary
 *     responses:
 *       200:
 *         description: 文件上传成功
 *       400:
 *         description: 文件上传失败
 */
router.post('/upload', protect, upload.single('file'), handleMulterError, uploadFile);

/**
 * @swagger
 * /posts/publish:
 *   post:
 *     summary: 发布帖子
 *     tags: [Post]
 *     security:
 *       - bearerAuth: []
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             properties:
 *               title:
 *                 type: string
 *               content:
 *                 type: string
 *               fileIds:
 *                 type: array
 *                 items:
 *                   type: string
 *             example:
 *               title: "测试帖子"
 *               content: "这是一个测试帖子"
 *               fileIds: ["64b8f1b5e4b0f5b5f0f5b5f0"]
 *     responses:
 *       201:
 *         description: 发布成功
 *       400:
 *         description: 标题和内容不能为空
 *       500:
 *         description: 发布失败，请稍后重试
 */
// 发布帖子（支持图片和文档上传）
router.post('/publish', protect, upload.fields([
  { name: 'image', maxCount: 1 },
  { name: 'file', maxCount: 1 }
]), handleMulterError, publishPost);

/**
 * @swagger
 * /posts/publish:
 *   get:
 *     summary: 获取帖子列表
 *     tags: [Post]
 *     security:
 *       - bearerAuth: []
 *     responses:
 *       200:
 *         description: 返回帖子列表
 */
router.get('/', getPosts);

/**
 * @swagger
 * /posts/paged:
 *   get:
 *     summary: 分页获取帖子列表
 *     tags: [Post]
 *     security:
 *       - bearerAuth: []
 *     parameters:
 *       - in: query
 *         name: page
 *         required: false
 *         schema:
 *           type: integer
 *         description: 页码，默认为1
 *       - in: query
 *         name: limit
 *         required: false
 *         schema:
 *           type: integer
 *         description: 每页数量，默认为10，最大值为50
 *       - in: query
 *         name: category
 *         required: false
 *         schema:
 *           type: string
 *         description: 分类ID
 *       - in: query
 *         name: search
 *         required: false
 *         schema:
 *           type: string
 *         description: 搜索关键词
 *     responses:
 *       200:
 *         description: 返回分页的帖子列表
 */
router.get('/paged', getPostsPaged);

/**
 * @swagger
 * /posts/publish/{id}:
 *   delete:
 *     summary: 删除帖子
 *     tags: [Post]
 *     security:
 *       - bearerAuth: []
 *     parameters:
 *       - in: path
 *         name: id
 *         required: true
 *         schema:
 *           type: string
 *         description: 帖子ID
 *     responses:
 *       200:
 *         description: 帖子已删除
 *       404:
 *         description: 帖子不存在
 */
router.delete('/publish/:id', protect, deletePost);

/**
 * @swagger
 * /posts/{id}:
 *   get:
 *     summary: 获取单个帖子详情
 *     tags: [Post]
 *     parameters:
 *       - in: path
 *         name: id
 *         required: true
 *         schema:
 *           type: string
 *         description: 帖子ID
 *     responses:
 *       200:
 *         description: 返回帖子详情
 *       404:
 *         description: 帖子不存在
 */
router.get('/:id', protect, getById);

/**
 * @swagger
 * /posts/{id}/like:
 *   post:
 *     summary: 点赞/取消点赞帖子
 *     tags: [Post]
 *     security:
 *       - bearerAuth: []
 *     parameters:
 *       - in: path
 *         name: id
 *         required: true
 *         schema:
 *           type: string
 *         description: 帖子ID
 *     responses:
 *       200:
 *         description: 操作成功
 *       404:
 *         description: 帖子不存在
 *       500:
 *         description: 操作失败，请稍后重试
 */
router.post('/:id/like', protect, toggleLike);

module.exports = router;